package cn.edu.jmu.oelp.controller;


import cn.edu.jmu.oelp.pojo.RespCode;
import cn.edu.jmu.oelp.pojo.RespEntity;
import cn.edu.jmu.oelp.pojo.User;
import cn.edu.jmu.oelp.service.UserService;
import cn.edu.jmu.oelp.utils.SendSmsUtil;
import cn.edu.jmu.oelp.utils.VerificationCodeUtil;
import com.google.gson.Gson;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class SmsController {
    @Autowired
    private SendSmsUtil sendSmsUtil;

    @Autowired
    private UserService userService;

    @Data
    public static class SmsData {
        String code;

        public SmsData(String code) {
            this.code = code;
        }
    }


    /**
     * 发送验证码
     *
     * @param phoneNumber 手机号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendSms")
    public RespEntity sendSms(String phoneNumber, HttpServletRequest request) {
        //随机生成验证码
        String numeral = VerificationCodeUtil.getNumeral();
        SmsData smsData = new SmsData(numeral);
        Gson gson = new Gson();
        String code = gson.toJson(smsData);
        String information = sendSmsUtil.aliSendSms(phoneNumber, code);
        //session.setAttribute(phoneNumber,numeral);
        request.getServletContext().setAttribute(phoneNumber, numeral);
        //System.out.println("发送时存入session的验证码是"+session.getAttribute(phoneNumber));
        //.out.println("发送时手机号是"+phoneNumber);
        //System.out.println("发送时验证码是"+numeral);
        if (information.equals("success")) {
            return new RespEntity(RespCode.SUCCESS);
        }
        return new RespEntity(RespCode.WARN);
    }
}
